<template>
    <div style="background-color: #ececec; padding: 10px;">
        <a-row :gutter="[12,12]">
            <a-col :span="24">
                <div class="formBox">
                    <a-form-model layout="inline" @submit="handleSubmit" @submit.native.prevent>
                        <a-form-model-item class="width100">
                            <a-input v-model="searchForm.code"
                                     :allowClear="$store.getters.allowClear"
                                     placeholder="人员编号"></a-input>
                        </a-form-model-item>
                        <a-form-model-item class="width100">
                            <a-input v-model="searchForm.name"
                                     :allowClear="$store.getters.allowClear"
                                     placeholder="人员姓名"></a-input>
                        </a-form-model-item>
                        <!--部门-->
                        <a-form-model-item>
                            <DeptSelect class="width120"
                                        :value="searchForm.deptCode"
                                        @deptSelectResult="(e)=>{ searchForm.deptCode=e }"
                            />
                        </a-form-model-item>
                        <!-- 职务-->
                        <a-form-model-item>
                            <PositionSelect :code="searchForm.positionCode" class="width120"
                                            :placeholder="'职务岗位'"
                                            @positionSelectResult="(e)=>{ searchForm.positionCode=e ;}"
                            />
                        </a-form-model-item>
                        <!-- 分组-->
                        <a-form-model-item class="width120">
                            <GroupSelect :code="searchForm.groupCode" class="width120"
                                         :placeholder="'标签分组'"
                                         @groupSelectResult="(e)=>{ searchForm.groupCode=e ;}"
                            />
                        </a-form-model-item>
                        <a-form-model-item class="width100">
                            <a-button icon="search" type="primary" html-type="submit">搜索</a-button>
                        </a-form-model-item>
                    </a-form-model>
                </div>
            </a-col>
            <a-col :span="14">
                <div class="formBox">
                    <!-- 表格开始 -->
                    <a-table bordered
                             :columns="columns"
                             :row-key="record => record.staffCode"
                             :data-source="leftTableDatas"
                             :pagination="pagination"
                             :loading="loading"
                             @change="handleTableChange"
                             :row-selection="rowSelection"
                             size="small"
                             :scroll="{y:250}"
                    >
                        <template slot="title" slot-scope="currentPageData">
                            <small class="text-danger text-right"> 人员列表 </small>
                        </template>
                    </a-table>
                </div>
            </a-col>
            <a-col :span="10">
                <div class="formBox">
                    <a-table :columns="selectColumns"
                             :data-source="rightTableDatas"
                             :scroll="{y:280}"
                             :pagination="selectPagination"
                             size="small"
                             :row-key="record => record.staffCode"
                             bordered
                    >
                        <template slot="title" slot-scope="currentPageData">
                            <small class="text-danger text-right"> 已选 <b>{{hasSelctTotal}}</b> 人 </small>
                        </template>
                        <template slot="operation" slot-scope="text, record">
                            <a @click="removeRecord(record)">移除</a>
                        </template>
                    </a-table>
                </div>
            </a-col>
        </a-row>
    </div>
</template>
<script>

    import {pagination, staffDictTable} from '../public/colums';
    import {staffByMultiple} from "../../../util/internal.api";

    export default {
        props: ["valueList"],
        components: {
            //部门ID选择器
            DeptSelect: () => import('./DeptSelector'),
            //职务选择器
            PositionSelect: () => import('./PositionSelector'),
            //分组选择器
            GroupSelect: () => import('./GroupSelector')
        },
        data() {
            return {
                rightTableDatas: [],
                //搜索条件
                searchForm: {
                    status: 'T', //只显示在职人员
                    code: '',
                    name: '',
                    deptCode: undefined,
                    positionCode: undefined,
                    groupCode: undefined,
                },
                //已选人员数据
                selectPagination: false,
                selectColumns: [
                    {
                        title: '编号',
                        dataIndex: 'staffCode',
                        width: 90,
                    },
                    {
                        title: '姓名',
                        dataIndex: 'staffName',
                    },
                    {
                        title: '操作',
                        align: 'center',
                        width: 80,
                        scopedSlots: {customRender: 'operation'},
                    },
                ],
                loading: false, //表格loading
                pagination: {
                    ...pagination
                }, //复制预设的分页参数
                leftTableDatas: [],
                columns: staffDictTable,
                rowSelection: {
                    hideDefaultSelections: false,  //不要全选和反选
                    selectedRowKeys: [],
                    onChange: this.onSelectChange,
                }
            };
        },
        methods: {
            //1.0 获取表格数据
            getTableList() {
                this.loading = true;
                //删除对象中的空值
                let searchData = this.$exMod.filterObjEmpty(this.searchForm);
                staffByMultiple(this.pagination, searchData).then(res => {
                    this.loading = false;
                    if (res.code === 0) {
                        this.leftTableDatas = res.data.result; //表格数据
                        this.pagination.total = res.data.total; //总记录条数
                        //默认选中的数据肌酸 重新获取被选中的数据
                        this.getIndex();
                    }
                });
            },
            //1.2翻页监听
            handleTableChange(pagination) {
                this.pagination.current = pagination.current;
                this.pagination.pageSize = pagination.pageSize;
                this.initData();
            },
            //1.3 数据搜索
            handleSubmit(e) {
                this.pagination.current = 1;
                this.initData();
            },
            //数据初始化
            async initData() {
                await this.getTableList()
            },
            //======================初始化组件数据================
            //表格初始化算中的数据
            getIndex() {
                let indexArr = [];
                if (this.rightTableDatas.length > 0) {
                    let hasCodeArr = this.rightTableDatas.map(item => item.staffCode);
                    let bj;
                    for (let i = 0; i < this.leftTableDatas.length; i++) {
                        bj = hasCodeArr.includes(this.leftTableDatas[i].code);
                        if (bj) {
                            indexArr.push(i);
                        }
                    }
                }
                this.rowSelection.selectedRowKeys = indexArr;
            },
            //需要新增的人员的数组集合
            addStaff(NeedAddArr) {
                this.rightTableDatas = [...this.rightTableDatas, ...NeedAddArr];
            },
            removeStaff(NeedDelIds) {
                let newArr = this.rightTableDatas.filter(function (item, index) {
                    //循环当前数组 返回不需要删除的数组 拼接成新数组
                    return !NeedDelIds.includes(index)
                });
                //把新数组解构复制给选中的数据 用来展示和返回
                this.rightTableDatas = [...newArr];
            },
            //==========操作人员数据变化==============
            removeRecord(obj) {
                let hasCodeArr = this.rightTableDatas.map(item => item.staffCode);
                let lszb = hasCodeArr.findIndex((value, index, arr) => {
                    return value === obj.staffCode;
                });
                let NeedDelIds = [];
                NeedDelIds.push(lszb);
                this.removeStaff(NeedDelIds);
                //删除左边表格
                let arr = this.rowSelection.selectedRowKeys;
                //删除这个卓彪
                this.leftTableDatas.findIndex((item, index) => {
                    if (item.code === obj.staffCode) {
                        if (index > -1) {
                            arr.splice(arr.findIndex(item => item === index), 1)
                        }
                        return index;
                    }
                });
                //通知父组件接收新值
                this.sendNewData();
            },
            //表格选择
            onSelectChange(selectedRowKeys) {
                //获取所有被选中人员的代码
                let hasCodeArr = this.rightTableDatas.map(item => item.staffCode);
                //本页已被训中的人
                let NeedDelIds = [];
                //本业没有被选中的人
                let NeedAdd = [];
                //返回被选中的数据在表格中的位置数组
                this.rowSelection.selectedRowKeys = selectedRowKeys;
                for (let i = 0; i < this.leftTableDatas.length; i++) {
                    //是否被历史选中
                    let T1 = hasCodeArr.includes(this.leftTableDatas[i].code);
                    //是否被新选中
                    let T2 = selectedRowKeys.includes(i);
                    let staffCode = this.leftTableDatas[i].code;
                    //历史有选 现在没选 删除坐标
                    if (T1 && !T2) {
                        //历史坐标
                        let lszb = hasCodeArr.findIndex((value, index, arr) => {
                            return value === staffCode;
                        });
                        NeedDelIds.push(lszb);
                    }
                    //历史有没有 选在 优选 加入坐标
                    if (!T1 && T2) {
                        let obj = {staffCode: this.leftTableDatas[i].code, staffName: this.leftTableDatas[i].name}
                        //新加的选中
                        NeedAdd.push(obj);
                    }
                }
                //执行删除
                if (NeedDelIds.length > 0) {
                    this.removeStaff(NeedDelIds);
                }
                //执行新增
                if (NeedAdd.length > 0) {
                    this.addStaff(NeedAdd);
                }
                //通知父组件接收新值
                this.sendNewData();
            },
            //发送变更后的数据给父组件
            sendNewData() {
                this.$emit('callBack', this.rightTableDatas);
            },
        },
        created() {
            //弹窗页面 微调一次分页数量
            this.pagination.pageSize = 6;
            this.initData();
        },
        computed: {
            hasSelctTotal() {
                return this.rightTableDatas.length;
            }
        },
        watch: {
            valueList(val) {
                this.rightTableDatas = [...val];
            }
        }
    };
</script>
<style scoped>
    .width100 {
        width: 100px;
    }

    .width120 {
        width: 120px;
    }

    .formBox {
        background-color: white;
        padding: 8px;
    }
</style>
